package com.woniuxy.movice.handler;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.woniuxy.movice.config.AliPayConfig;
import com.woniuxy.movice.entity.Orders;
import com.woniuxy.movice.entity.Users;
import com.woniuxy.movice.exception.AuthException;
import com.woniuxy.movice.exception.OrderException;
import com.woniuxy.movice.pojo.Order;
import com.woniuxy.movice.service.OrderService;
import com.woniuxy.movice.service.PayService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api("支付接口")
@Controller
@RequestMapping("pay")
public class PayHandler {

	@Autowired
	private OrderService orderService;
	@Autowired
	private PayService payService;

	/**
	 * 支付接口
	 * 
	 * @param orderId
	 * @param session
	 * @return
	 * @throws AlipayApiException
	 * @throws OrderException
	 */
	@ApiOperation(value="支付接口",notes="订单orderId")
	@PostMapping("pay")
	@ResponseBody
	public String pay(Integer orderId, HttpSession session) throws AlipayApiException, OrderException ,AuthException{
		Users user = (Users) session.getAttribute(session.getId());
		Order order = orderService.findOrderByID(orderId);
		// 订单中的uid不等于登录用户id
		if (!user.getUid().equals(order.getUser().getUid())) {
			throw new AuthException("账户异常");
		}
		if(!order.getOstate().equals(1)){
			throw new OrderException("订单状态已改变");
		}
		String out_trade_no = order.getOnum();
		String subject = order.getMovie().getMname() + "购票";
		String total_amount = order.getOprice().toString();
		String body = order.getMovie().getMname() + ":" + order.getSelectedSets();
		return payService.pay(out_trade_no, subject, total_amount, body);
	}

	/**
	 * 获取支付宝返回信息
	 * @param request
	 * @param out_trade_no
	 * @param trade_no
	 * @param trade_status
	 * @throws AlipayApiException
	 */
	@ApiOperation(value="获取支付宝返回信息",notes="获取支付宝返回信息")
	@RequestMapping(value = "save")
	@ResponseBody
	public void getResponseInfor(HttpServletRequest request, String out_trade_no, String trade_no, String trade_status)
			throws AlipayApiException {
		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map<String, String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		boolean signVerified = AlipaySignature.rsaCheckV1(params, AliPayConfig.alipay_public_key, AliPayConfig.charset,
				AliPayConfig.sign_type); // 调用SDK验证签名
		if (signVerified) {// 验证成功
			if (trade_status.equals("TRADE_SUCCESS")) {
				/**
				 * 如果交易完成，更新订单流水号，插入付款时间
				 */
				Orders orders = new Orders();
				orders.setOnum(out_trade_no);
				// 插入流水号
				orders.setPayCode(trade_no);
				// 插入付款时间
				orders.setPtime(new Date());
				// 表示已付款
				orders.setOstate(2);
				orderService.updateOrderByOnum(orders);
			}
		}
	}
	@RequestMapping("show/{out_trade_no}")
	public ModelAndView showOrderInfoHtml(@PathVariable("out_trade_no")String out_trade_no){
		ModelAndView modelAndView=new ModelAndView("orderInfo");
		modelAndView.addObject("orderNum", out_trade_no);
		return modelAndView;
	}
	
	@ResponseBody
	@RequestMapping("/refund")
	public String refund(HttpServletRequest request,HttpServletResponse response, String onumber,String opay,String amount) throws IOException, AlipayApiException{
		String mess="退款失败！";
		//获得初始化的AlipayClient
		AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.gatewayUrl, AliPayConfig.app_id, AliPayConfig.merchant_private_key, "json", AliPayConfig.charset, AliPayConfig.alipay_public_key, AliPayConfig.sign_type);
		
		//设置请求参数
		AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
		
/*		//商户订单号，商户网站订单系统中唯一订单号
		String out_trade_no = new String(request.getParameter("WIDTRout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
		//支付宝交易号
		String trade_no = new String(request.getParameter("WIDTRtrade_no").getBytes("ISO-8859-1"),"UTF-8");
		//请二选一设置
		//需要退款的金额，该金额不能大于订单金额，必填
		String refund_amount = new String(request.getParameter("WIDTRrefund_amount").getBytes("ISO-8859-1"),"UTF-8");
		//退款的原因说明
		String refund_reason = new String(request.getParameter("WIDTRrefund_reason").getBytes("ISO-8859-1"),"UTF-8");
		//标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
		String out_request_no = new String(request.getParameter("WIDTRout_request_no").getBytes("ISO-8859-1"),"UTF-8");*/
		
		alipayRequest.setBizContent("{\"refund_amount\":\""+ amount +"\"," 
				+ "\"trade_no\":\""+ opay +"\"}");
		
		//请求
		String result = alipayClient.execute(alipayRequest).getBody();
		//成功后修改数据库状态
		if(result.contains("Success")){
			orderService.updateRefund(onumber, 6);
			mess="退款成功！";
		}
		//输出
		//response.getWriter().println(result);
		return mess;
	}
}
